package com.jzqf.android.alive.navi

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Toast
import com.baidu.mapapi.CoordType
import com.baidu.mapapi.SDKInitializer
import com.baidu.navisdk.adapter.BNRoutePlanNode
import com.baidu.navisdk.adapter.BaiduNaviManagerFactory
import com.baidu.navisdk.adapter.IBNRoutePlanManager
import com.baidu.navisdk.adapter.IBaiduNaviManager
import com.baidu.navisdk.adapter.struct.BNTTsInitConfig
import com.baidu.navisdk.adapter.struct.BNaviInitConfig

object NaviManager {
    private const val TAG = "NaviManager"
    private var applicationContext: Context? = null
    fun initSdk(context: Context?, options: InitNaviOptions) {
        if (context == null) {
            options.fail?.invoke(-1, "initSdk失败，context is null!")
            return
        }
        applicationContext = context
        SDKInitializer.setAgreePrivacy(applicationContext, true)
        SDKInitializer.initialize(applicationContext)
        SDKInitializer.setCoordType(CoordType.GCJ02)
        initNavi(options)
    }

    private fun initNavi(options: InitNaviOptions) {
        if (BaiduNaviManagerFactory.getBaiduNaviManager().isInited) {
            return
        }

        val config: BNaviInitConfig? = BNaviInitConfig.Builder()
            .naviInitListener(object : IBaiduNaviManager.INaviInitListener {
                override fun onAuthResult(status: Int, msg: String?) {
                    val result: String?
                    if (0 == status) {
                        result = "key校验成功!"
                        options.success?.invoke(status, "key校验成功")
                    } else {
                        result = "key校验失败, $msg"
                        options.fail?.invoke(status, "key校验失败, $msg")
                    }
                    Log.e(TAG, result)
                    Toast.makeText(applicationContext, result, Toast.LENGTH_SHORT).show()
                }

                override fun initStart() {
                    Log.e(TAG, "initStart")
                    BaiduNaviManagerFactory.getBaiduNaviManager().enableOutLog(true)
                }

                override fun initSuccess() {
                    Log.e(TAG, "initSuccess ")
                    options.success?.invoke(1, "百度导航初始化成功")
                    // 初始化tts
//                    initTTS(naviInitParam)
                    applicationContext?.sendBroadcast(Intent("com.navi.ready"))
                    Toast.makeText(applicationContext, "百度导航初始化成功", Toast.LENGTH_SHORT)
                        .show()
                }

                override fun initFailed(errCode: Int) {
                    Log.e(TAG, "initFailed = $errCode")
                    options.fail?.invoke(errCode, "百度导航初始化失败")
                    Toast.makeText(
                        applicationContext,
                        "百度导航初始化失败,errCode=${errCode}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }).build()
        BaiduNaviManagerFactory.getBaiduNaviManager().init(applicationContext, config)
    }

    private fun initTTS(options: InitNaviOptions) {
        // 使用内置TTS
        val config: BNTTsInitConfig? =
            BNTTsInitConfig.Builder().context(applicationContext).appId(options.appIdTTS)
                .appKey(options.appKeyTTS).secretKey(options.secretKeyTTS).authSn(options.authSnTTS)
                .build()
        BaiduNaviManagerFactory.getTTSManager().initTTS(config)
    }


    /**
     * 路径规划
     * 坐标系: gcj02
     */
    fun routePlanToNavi(options: StartNaviOptions) {
        try {
            val startNode: BNRoutePlanNode? =
                BNRoutePlanNode.Builder().latitude(options.startLatitude)
                    .longitude(options.startLongitude).build()
            val endNode: BNRoutePlanNode? = BNRoutePlanNode.Builder().latitude(options.endLatitude)
                .longitude(options.endLongitude).build()
            val list: MutableList<BNRoutePlanNode?> = ArrayList()
            list.add(startNode)
            list.add(endNode)
            // 确保至少有两个节点
            if (list.size < 2) {
                Toast.makeText(applicationContext, "起点或终点节点获取失败", Toast.LENGTH_SHORT)
                    .show()
                options.fail?.invoke(-1, "起点或终点节点获取失败")
                return
            }
            // 关闭电子狗
            if (BaiduNaviManagerFactory.getCruiserManager().isCruiserStarted) {
                BaiduNaviManagerFactory.getCruiserManager().stopCruise()
            }
            //设置多条路线
            BaiduNaviManagerFactory.getCommonSettingManager().setMultiRouteEnable(true);
            BaiduNaviManagerFactory.getRoutePlanManager().routePlan(
                list,
                IBNRoutePlanManager.RoutePlanPreference.ROUTE_PLAN_PREFERENCE_DEFAULT,
                null,
                object : Handler(Looper.getMainLooper()) {
                    override fun handleMessage(msg: Message) {
                        when (msg.what) {
                            IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_START -> {
                                options.success?.invoke(1000, "算路开始")
                            }

                            IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_SUCCESS -> {
                                options.success?.invoke(1002, "算路成功")
                            }

                            IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_FAILED -> {
                                options.fail?.invoke(1003, "算路失败")
                            }

                            IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_TO_NAVI -> {
                                options.success?.invoke(8000, "算路成功准备进入导航")
                                val intent =
                                    Intent(applicationContext, NaviGuideActivity::class.java)
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                applicationContext?.startActivity(intent)
                            }

                            else -> {
                                options.fail?.invoke(msg.what, "未知状态")
                            }
                        }
                    }
                })
        } catch (e: Exception) {
            e.printStackTrace()
            val errorMsg = "导航规划异常: ${e.message}"
            options.fail?.invoke(-1, errorMsg)
        }
    }
}
